package cn.xhh.dailyreview.server.utils;

import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;

import cn.xhh.dailyreview.server.dao.CategoryDAO;
import cn.xhh.dailyreview.server.dao.UserDAO;
import cn.xhh.dailyreview.server.model.Category;
import cn.xhh.dailyreview.server.model.User;

public class DbUtil {
	
	private static final Logger logger = Logger.getLogger(DbUtil.class.getName());
	
	private static final PersistenceManagerFactory pmfInstance = 
		JDOHelper.getPersistenceManagerFactory("transactions-optional");
	
	static {
		init();
	}

	public static PersistenceManagerFactory getPMF() {
		return pmfInstance;
	}

	/**
	 * initialize the admin account
	 */
	private static void init() {
		logger.config("DbUtil.init()");
		
		UserDAO userDao = new UserDAO();
		if (userDao.readCount() > 0)
			return;
		
		/* no users in DB, initialize an admin account */
		logger.info("init admin account...");
		User user = new User("admin", Utility.md5Digest("admin"));
		user.setConfirmed(true);
		userDao.createOrUpdate(user);
		CategoryDAO categoryDao = new CategoryDAO();
		for (String review : PropertiesDef.getDefaultReviewsZh())
			categoryDao.create(new Category(user, review));
	}

}
